import { BadRequestException, Body, Controller, Post } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CountResDto } from '../../common/dtos/count.res.dto';
import { MultiPublishReqDto } from '../dtos/multi-publish.req.dto';
// import { MultiPublishReqDto } from '../dtos/multi-publish.req.dto';
import { SinglePublishReqDto } from '../dtos/single-publish.req.dto';
import { MqttPublishService } from '../services/mqtt-publish.service';

@ApiTags('device mqtt simulate')
@Controller('device/simulate')
export class DeviceMqttSimulateController {
  constructor(private readonly mqttPublishService: MqttPublishService) {}

  @ApiOperation({ summary: '单台模拟' })
  @Post('single')
  async singlePublish(@Body() body: SinglePublishReqDto): Promise<CountResDto> {
    const time = body.times || 1;
    let successCount = 0;
    for (let i = 0; i < time; i++) {
      const { success, error } = await this.mqttPublishService.publish(body.topic, body.payload);

      if (success) successCount++;
      if (error) throw new BadRequestException(`${error.message}`);
    }
    return { count: successCount };
  }

  @ApiOperation({ summary: '多台模拟' })
  @Post('multi')
  async multiPublish(@Body() body: MultiPublishReqDto): Promise<CountResDto> {
    const random = () => {
      const min = -100;
      const max = 100;
      return Math.floor(Math.random() * (max - min)) + min;
    };

    const time = body.times || 1;
    let successCount = 0;
    for (const device of body.device_list) {
      for (let i = 0; i < time; i++) {
        const payload = {
          Uploadbeat: 1482,
          Config: -1,
          Status: 0,
          CSQ: 23,
          MN: device,
          AlarmValue: 70,
          VOCS: [1600 + random(), 1600 + random(), 1600 + random(), 1600 + random(), 1600 + random(), 1600 + random()],
          CONS: [400 + random(), 400 + random(), 400 + random(), 400 + random(), 400 + random(), 400 + random()],
          BaseLine: 1652
        };
        console.log(random());
        const { success, error } = await this.mqttPublishService.publish(body.topic_temp + device, payload);

        if (success) successCount++;
        if (error) throw new BadRequestException(`${error.message}`);
      }
    }

    return { count: successCount };
  }
}
